from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
from numpy import floor
from numpy import abs
import time
from perlin_noise import PerlinNoise 

app = Ursina()

#window
window.color = color.rgb(0, 30, 0)
window.exit_button.visible = False

#time
prevTime = time.time()

#scene
scene.fog_color  = color.rgb(144, 255, 255)
scene.fog_density = 0.02

#textures
dirt_texture = load_texture('dirt.jpg')
poo_texture  = load_texture('poo.png')

#models
poo_model = load_model('poo.obj')

#variables
seed = 2024
terrain_width  = 100
amp = 32
freq = 100
sci = 0
currentSubset = 0

#input
def input(key):
    if key == 'q' or key == 'escape':
        quit()

#update
def update():
    global prevZ, prevX, prevTime
    if  abs(player.z - prevZ) > 1 or \
        abs(player.x - prevX) > 1:
            generate_colliders()

    if time.time() - prevTime > 0.5:
        generateSubset()
        prevTime = time.time()

#terrain
terrain = Entity(model=None, collider=None)
noise  = PerlinNoise(octaves=2, seed=seed)
subWidth = terrain_width
subsets = []
subCubes = []

colliders = []
colliders_width  = 6
for i in range(colliders_width*colliders_width):
    chunk  = Entity(model='cube',Collider='box')
    colliders.append(chunk)

def generate_colliders():
    global colliders_width, amp, freq
    for i in range(len(colliders)):
        x = colliders[i].x = floor((i/colliders_width) + player.x)
        z = colliders[i].z = floor((i%colliders_width) + player.z)
        colliders[i].y = floor((noise([x/freq,z/freq]))*amp)

#player
player = FirstPersonController()
player.cursor.visible = False
player.gravity = 0.5
player.x = player.z = 5
player.y = 12
prevZ = player.z
prevX = player.x

#entity
poo = Entity(model=poo_model,scale=1,
             x=22,y=7.1,z=16,
             texture=poo_texture,
             double_sided=True)

generate_colliders()

app.run()